package com.ja.sevice.impl;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ja.config.WebsiteStateConfig;
import com.ja.dao.BankMapper;
import com.ja.dao.JineMapper;
import com.ja.dao.RechargeInterfaceMapper;
import com.ja.dao.RechargeQueryMapper;
import com.ja.dao.UserMapper;
import com.ja.domain.AdminUser;
import com.ja.domain.BankCard;
import com.ja.domain.Jine;
import com.ja.domain.PagingData;
import com.ja.domain.PayMoney;
import com.ja.domain.RechargeInterface;
import com.ja.domain.TodayRecord;
import com.ja.domain.User;
import com.ja.sevice.IActivityService;
import com.ja.sevice.JineService;
import com.ja.sevice.LiushuiService;
import com.ja.sevice.YunyingbbService;
import com.ja.util.DateUtil;
import com.ja.util.HttpClientUtil;
import com.ja.util.JsonResult;
import com.ja.util.MD5Util;
import com.ja.util.WebSocketJson;

@Service
public class JineServiceImpl implements JineService {
	
	@Autowired
	private JineMapper jineMapper;
	
	@Autowired
	private RechargeInterfaceMapper rechargeInterfaceMapper;
	
	@Autowired
	private RechargeQueryMapper rechargeQueryMapper;
	
	@Autowired
	private BankMapper bankMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private LiushuiService liushuiService;
	
	@Autowired
	private IActivityService activityService;
	
	@Autowired
	private YunyingbbService yunyingbbService;

	private static boolean takeInverse;




	@Transactional
	@Override
	public ModelAndView insertRechargeOrder(String payType, Double money, User user, HttpServletRequest request) {
		ModelAndView model = new ModelAndView();
		DecimalFormat dec = new DecimalFormat("#0.00");
		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		List<RechargeInterface> recharge1 = rechargeInterfaceMapper.getRecharge();
		RechargeInterface recharge = recharge1.get(0);
		String userId = recharge.getP_UserId();//商户id
		String key = recharge.getSalfStr();//商户秘钥
		String rechargeURL = recharge.getPayInterfaceURL();//充值接口地址
		String orderNum = "CZ"+DateUtil.DateFormatOrderNum() + user.getId();//商户订单号
		String cardId = "";//点卡账号
		String cardPass = "";//点卡密码
		String faceVale = dec.format(money);//充值金额
		String shopName = recharge.getShopName();//商品名称
		String price = "1";//商品单价
		String shopCount = "1";//商品数量
		String description = "10001";//网银银行编号
		String notice = "welcome recharge";//附加信息字段
		String notifyURL = url + "/pay/payNotifyTwo.do";//支付后异步通知地址
		String resultURL = url + "/pay/payReturnTwo.do";//支付同步跳转地址
		String ChannelId = "";//支付方式
		String recharges = "";
		
		switch(payType) {
			case "1":
				ChannelId = "33";
				recharges = "微信钱包";
				break;
			case "2":
				ChannelId = "21";
				recharges = "微信扫码";
				break;
			case "3":
				ChannelId = "01";
				recharges = "支付宝钱包";
				break;
			case "4":
				ChannelId = "02";
				recharges = "支付宝扫码";
				break;
			case "5":
				ChannelId = "92";
				recharges = "QQ钱包";
				break;
			case "6":
				ChannelId = "89";
				recharges = "QQ扫码";
				break;
			case "7":
				ChannelId = "98";
				recharges = "银联快捷";
				break;
			case "8":
				ChannelId = "95";
				recharges = "银联扫码";
				break;
		}
		StringBuffer PostKey = new StringBuffer();
		PostKey.append(userId).append("|").append(orderNum).append("|").append(cardId).append("|").append(cardPass)
				.append("|").append(faceVale).append("|").append(ChannelId).append("|").append(key);
		String post_key = MD5Util.encryption(PostKey.toString()).toLowerCase();//签名加密
		
		PayMoney pay = new PayMoney();
		pay.setUserId(userId);
		pay.setOrderNum(orderNum);
		pay.setCardId(cardId);
		pay.setCardPass(cardPass);
		pay.setFaceValue(faceVale);
		pay.setChannelId(ChannelId);
		pay.setGoodsName(shopName);
		pay.setGoodsPrice(price);
		pay.setGoodsCount(shopCount);
		pay.setBankId(description);
		pay.setRemarks(notice);
		pay.setPostKey(post_key);
		pay.setResultURL(resultURL);
		pay.setNotifyURL(notifyURL);
		pay.setPayInterfaceURL(rechargeURL);
		model.addObject("pay", pay);

		Jine jine = new Jine();// 存入充值信息
		jine.setName(user.getName());
		jine.setOrdernum(orderNum);
		jine.setZhifupt(recharges);
		jine.setFukuanje(Double.parseDouble(faceVale));
		jine.setCkname("-");
		jine.setZhifuzh("-");
		jine.setHydengji("在线");
		jine.setSqtime(DateUtil.getCurrTime());
		jine.setCltime(DateUtil.getCurrTime());
		jine.setType("在线充值");
		jine.setState("未支付");
		jine.setCaozuo("已操作");
		jine.setCzname("系统自动");
		jine.setStatus(0);
		jine.setBeizhu("在线充值");
		jine.setUserid(user.getId());
		jineMapper.addJilu(jine);
		
		PayMoney pays = new PayMoney();// 存入在线充值信息
		pays.setUserId(userId);
		pays.setOrderNum(orderNum);
		pays.setCardId("-1");
		pays.setChannelId(ChannelId);
		pays.setFaceValue(faceVale);
		pays.setPostKey(post_key);
		pays.setUid(user.getId());
		return model;
	}

	@Transactional
	@Override
	public JsonResult payNotifys(PayMoney pay, User users) {
		String message = "";
		AdminUser admin = new AdminUser();
		admin.setName("系统自动");
		User user = userMapper.getUserByid(users.getId());
		String orderNum = pay.getOrderNum();// 商户订单号
		String faceValue = pay.getFaceValue();// 实际交易金额
		String postKey = pay.getPostKey();// 加密签名

		Jine jine = jineMapper.findJineInfo(pay.getOrderNum());//查询充值订单
		if(jine==null) {
			return new JsonResult("success","充值信息有误,没有当前订单!");
		}
		PayMoney pay1 = rechargeQueryMapper.findByIdOrNumRechargeInfo(pay);//发货处理
		if(pay1==null) {
			return new JsonResult("success","当前订单已处理完成!,请勿重复提交!");
		}
		if(postKey.equals(pay1.getPostKey())) {
			if(Integer.parseInt(pay.getErrCode())==0) {
				if(Integer.parseInt(pay.getFaceValue())==Integer.parseInt(pay1.getFaceValue())) {
					updateRechargeState(pay.getId(), 2,  "充值成功", orderNum);
					double amount = Double.parseDouble(faceValue);
					liushuiService.changeRecord(user, admin,orderNum, amount, null, "在线充值", 1);//用户充值接口
					activityService.Recharge(user, orderNum,amount, "在线充值");//充值活动赠送
					message = "充值成功!";
				}else {
					updateRechargeState(pay.getId(), 3,  "充值失败", orderNum);
					message = "实际支付金额不匹配，充值失败!";
				}
			}else {
				updateRechargeState(pay.getId(), 3,  "充值失败", orderNum);
				message = "充值成功!";
			}
		}else {
			message = "签名信息有误，签名不匹配!";
		}
		return new JsonResult("success", message);
	}
	
	@Transactional
	@Override
	public String insertRechargeOrderTwo(String payType, Double moneys, User user, HttpServletRequest request) {
		List<RechargeInterface> recharges = rechargeInterfaceMapper.getRecharge();
		RechargeInterface recharge = recharges.get(0);//支付接口配置信息
		String recharge_type ="";
		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();//当前域名地址
		String partner_key = recharge.getSalfStr();//下单密钥
		String callback_key = recharge.getDealerURL();//回调秘钥
		String partner_no = recharge.getP_UserId();//商户编号
		String mch_order_no = "CZ"+DateUtil.DateFormatOrderNum() + user.getId();//订单编号
		String body = "apple";//商品名称
		String detail = "apple";//商品详情
		String money = moneys.intValue()+"00";//订单金额
		String attach = "appale";
		String rechargeURL = recharge.getPayInterfaceURL();//充值接口地址
		String callback_url = url + "/pay/payNotifysTwo.do";//异步通知接口
		String return_url = url + "/pay/payReturnTwo.do";//同步通知接口
		String time_stamp = String.format("%d", System.currentTimeMillis());
		String code_type = "";//支付类型 微信：1 --- 支付宝：2
		if("2".equals(payType)) {
			code_type = "1";
			recharge_type = "微信";
		}else if("4".equals(payType)) {
			code_type = "2";
			recharge_type = "支付宝";
		}
		String md5Url = "mch_order_no="+mch_order_no+"&money="+money+"&partner_no="+partner_no+"&time_stamp="+time_stamp+"&key="+partner_key;
		String token =  MD5Util.encryption(md5Url).toLowerCase();//加密的token
		Jine jine = new Jine();// 存入充值信息
		jine.setName(user.getName());
		jine.setOrdernum(mch_order_no);
		jine.setZhifupt(recharge_type);
		jine.setFukuanje(moneys);
		jine.setCkname("-");
		jine.setZhifuzh("-");
		jine.setHydengji("在线");
		jine.setSqtime(DateUtil.getCurrTime());
		jine.setCltime(DateUtil.getCurrTime());
		jine.setType("在线充值");
		jine.setState("未支付");
		jine.setCaozuo("已操作");
		jine.setCzname("系统自动");
		jine.setStatus(0);
		jine.setBeizhu("在线充值");
		jine.setUserid(user.getId());
		jineMapper.addJilu(jine);
		
		HttpClientUtil client = HttpClientUtil.getInstance();//请求支付
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("partner_no", partner_no);
		maps.put("mch_order_no", mch_order_no);
		maps.put("body", body);
		maps.put("detail", detail);
		maps.put("money", money+"");
		maps.put("attach", attach);
		maps.put("callback_url", callback_url);
		maps.put("return_url", return_url);
		maps.put("time_stamp", time_stamp);
		maps.put("code_type", code_type);
		maps.put("token", token);
		String result = client.sendHttpPost(rechargeURL, maps, "utf-8");
		Map<String,Object> map = JSON.parseObject(result);
		String order_no = (String)map.get("order_no");
		
		PayMoney pays = new PayMoney();// 存入在线充值信息
		String md5Urls = "mch_order_no="+mch_order_no+"&money="+money+"&order_no="+order_no+"&time_stamp="+time_stamp+"&key="+callback_key;
		String tokens =  MD5Util.encryption(md5Urls).toLowerCase();//加密的token
		pays.setUserId(partner_no);
		pays.setOrderNum(mch_order_no);
		pays.setCardId(order_no);
		pays.setChannelId(code_type);
		pays.setFaceValue(money+"");
		pays.setPostKey(tokens);
		pays.setUid(user.getId());
		pays.setRechargeType(Integer.parseInt(code_type));
		pays.setCreateTime(DateUtil.getCurrTime());
		rechargeQueryMapper.insertRechargeInfo(pays);
		return result;
	}
	
	@Transactional
	@Override
	public JsonResult payNotifysTwo(PayMoney pay) {
		String message = "";
		AdminUser admin = new AdminUser();
		admin.setName("系统自动");
		String orderNum = pay.getOrderNum();// 平台订单号
		String faceValue = pay.getFaceValue();// 实际交易金额
		String postKey = pay.getPostKey();// 加密签名

		Jine jine = jineMapper.findJineInfo(pay.getOrderNum());//查询充值订单
		if(jine==null) {
			return new JsonResult("success","充值信息有误,没有当前订单!");
		}
		PayMoney pay1 = rechargeQueryMapper.findByIdOrNumRechargeInfo(pay);//发货处理
		if(pay1==null) {
			return new JsonResult("success","当前订单已处理完成!,请勿重复提交!");
		}
		User user = userMapper.getUserByid(pay1.getUid());
		if(postKey.equals(pay1.getPostKey())) {
			if(Integer.parseInt(pay.getErrCode())==0) {
				if(Integer.parseInt(pay.getFaceValue())==Integer.parseInt(pay1.getFaceValue())) {
					updateRechargeState(pay.getId(), 2,  "充值成功", orderNum);
					double amount = Double.parseDouble(faceValue);
					liushuiService.changeRecord(user, admin,orderNum, amount, null, "在线充值", 1);//用户充值接口
					activityService.Recharge(user, orderNum,amount, "在线充值");//充值活动赠送
					message = "充值成功!";
				}else {
					updateRechargeState(pay.getId(), 3,  "充值失败", orderNum);
					message = "实际支付金额不匹配，充值失败!";
				}
			}else {
				updateRechargeState(pay.getId(), 3,  "充值失败", orderNum);
				message = "充值失败!";
			}
		}else {
			message = "签名不匹配,充值失败!";
		}
		return new JsonResult("success", message);
	}
	
	@Transactional
	@Override
	public synchronized JsonResult findPaymentResult(String order_no) {
		AdminUser admin = new AdminUser();
		PayMoney pay = new PayMoney();
		pay.setCardId(order_no);
		PayMoney pay1 = rechargeQueryMapper.findByIdOrNumRechargeInfo(pay);//发货处理
		if(pay1==null) {
			return new JsonResult("success","当前订单已处理完成!,请勿重复提交!");
		}
		List<RechargeInterface> recharges = rechargeInterfaceMapper.getRecharge();
		RechargeInterface recharge = recharges.get(0);//支付接口配置信息
		String partner_no = pay1.getUserId();
		String time_stamp = String.format("%d", System.currentTimeMillis());
		String rechargeURL = recharge.getPayQueryURL();//查询接口地址
		String partner_key = recharge.getSalfStr();//下单密钥
		String md5Url = "order_no="+order_no+"&partner_no="+partner_no+"&time_stamp="+time_stamp+"&key="+partner_key;
		String token =  MD5Util.encryption(md5Url).toLowerCase();//加密的token
		HttpClientUtil client = HttpClientUtil.getInstance();//请求支付
		String url = rechargeURL+"&order_no="+order_no+"&partner_no="+partner_no+"&time_stamp="+time_stamp+"&token="+token;
		String message = "";
		String result = client.sendHttpGet(url);//(rechargeURL, maps, "utf-8");
		JSONObject objs = JSON.parseObject(result);
		@SuppressWarnings("unchecked")
		Map<String,Object> maps = (Map<String, Object>) objs.get("data");
		String order_nos = (String)maps.get("order_no");
		String pay_status = (String)maps.get("pay_status");
		String orderNum = pay1.getOrderNum();
		String money = pay1.getFaceValue();
		double amount = Double.parseDouble(money.substring(0,money.length()-2));
		User user = userMapper.getUserByid(pay1.getUid());
		if(order_no.equals(order_nos)) {
			if(pay_status != null){
				if(pay_status.equals("1")) {
					message = "充值成功!";  
					updateRechargeState(pay1.getId(), 2,  "充值成功", pay1.getOrderNum());
					liushuiService.changeRecord(user, admin,orderNum, amount, null, "在线充值", 1);//用户充值接口
					activityService.Recharge(user, orderNum,amount, "在线充值");//充值活动赠送
				}else {
					message = "充值失败";
				}
			}
		}
		return new JsonResult("success",message);
	}

	public int updateRechargeState(Integer id, Integer state, String message, String orderNum) {
		if(id != 0) {
			rechargeQueryMapper.updateRechargeState(id,state);
		}
		jineMapper.updateRechargeState(message,orderNum,DateUtil.getCurrTime());
		return 0;
	}

	@Override
	public int addJilu(Jine jine) {
		return jineMapper.addJilu(jine);
	}
	
	@Override
	public List<Jine> getAllJl( Integer integer, int i,int model) {
		return jineMapper.getAllJl(integer,i,model);
	}

	@Override
	public List<Jine> getTypeJl(Integer integer, Integer i,Jine z, String date1, String date2,int model) {
		return jineMapper.getTypeJl(integer,i,z, date1, date2,model);
	}

	@Override
	public List<Jine> getTikuanJl(Integer integer, Integer integer2, int i) {
		return jineMapper.getTikuanJl(integer,integer2,i);
	}

	@Override
	public List<Jine> getTikuanTypeJl(Integer integer, Integer integer2,Jine z, String date1, String date2,int i) {
		return jineMapper.getTikuanTypeJl(integer,integer2,z, date1, date2,i);
	}

	@Override
	public Jine cxToday(String date) {
		return jineMapper.cxToday(date);
	}

	@Override
	public Jine zhCzJineJl(Integer id) {
		return jineMapper.zhCzJineJl(id);
	}

	@Override
	public Jine zhTkJineJl(Integer id) {
		return jineMapper.zhTkJineJl(id);
	}

	@Override
	public List<Jine> getOneCzJl(Jine z, String date1, String date2, Integer id) {
		return jineMapper.getOneCzJl(z, date1, date2, id);
	}

	@Override
	public List<Jine> getOneTkJl(Jine z, String date1, String date2, Integer id) {
		return jineMapper.getOneTkJl(z, date1, date2, id);
	}

	@Override
	public double getCzTodyJl(Integer id,String time) {
		return jineMapper.getCzTodyJl(id,time);
	}

	@Override
	public double getCzMonthJl(Integer id) {
		return jineMapper.getCzMonthJl(id);
	}
	
	@Override
	public int upTikuanSh(Jine jine) {
		return jineMapper.upTikuanSh(jine);
	}

	@Override
	public List<Jine> onechongzhi(Integer id) {
		return jineMapper.onechongzhi(id);
	}

	@Override
	public List<Jine> onetikuan(Integer id) {
		return jineMapper.onetikuan(id);
	}

	@Override
	public List<Jine> getAllJlLimit() {
		return jineMapper.getAllJlLimit();
	}
	
	@Override
	public int getTikuanCount(Integer id) {
		return jineMapper.getTikuanCount(id,DateUtil.findFormatDate());
	}

	@Override
	public int getTikuanCount1(Integer id) {
		return jineMapper.getTikuanCount1(id,DateUtil.findFormatDate());
	}

	@Override
	public int updateTikuansd(Jine j) {
		return jineMapper.updateTikuansd(j);
	}

	@Override
	public double getTikuanSum(Integer id) {
		return jineMapper.getTikuanSum(id,DateUtil.findFormatDate());
	}

	@Override
	public double getTikuanSum1(Integer id) {
		return jineMapper.getTikuanSum1(id,DateUtil.findFormatDate());
	}

	@Override
	public int getChongzhiCount(Integer id) {
		return jineMapper.getChongzhiCount(id,DateUtil.findFormatDate());
	}

	@Override
	public double getChongzhiSum(Integer id) {
		return jineMapper.getChongzhiSum(id,DateUtil.findFormatDate());
	}

	@Override
	public List<Jine> getByStateAllYuyin() {
		return jineMapper.getByStateAllYuyin();
	}

	@Override
	public double getCzLastMonthJl(Integer id) {
		return jineMapper.getCzLastMonthJl(id, DateUtil.findFormatDate());
	}

	@Override
	public Jine findInfoData() {
		Jine jines = jineMapper.findInfoData();
		if (jines!=null) {
			jineMapper.updateInfoData(jines.getId());
		}
		return jines;
	}

	@Override
	public List<Jine> findJineByState(Integer id) {
		return jineMapper.findJineByState(id);
	}

	@Override
	public int findJineByStateSuccess(Integer userid) {
		SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return jineMapper.findJineByStateSuccess(ss.format(new Date()).split("")[0],userid);
	}

	@Override
	public Jine findByIdJineInfo(Integer id) {
		return jineMapper.findByIdJineInfo(id);
	}

	@Override
	public List<Jine> findByTimeDetails(String currTime) {
		return jineMapper.findByTimeDetails(currTime);
	}

	@Override
	public List<Jine> findByDateUserIdInfo(Integer user_id, String date) {
		return jineMapper.findByDateUserIdInfo(user_id, date);
	}

	@Override
	public Integer getAllJlCounts() {
		return jineMapper.getAllJlCounts();
	}

	@Override
	public Integer getTypeJlCounts(Jine jine, String date1, String date2) {
		return jineMapper.getTypeJlCounts(jine, date1, date2);
	}

	@Override
	public Integer getTikuanJlCounts() {
		return jineMapper.getTikuanJlCounts();
	}

	@Override
	public Integer getTikuanTypeJlCounts(Jine jine, String date1, String date2) {
		return jineMapper.getTikuanTypeJlCounts(jine,date1,date2);
	}

	@Override
	public List<Jine> findMoneyRecord(PagingData paging,Jine jine) {
		List<Jine> jines = new ArrayList<>();
		if("2".equals(jine.getType())) {
			jines = jineMapper.findMoneyRecord2(paging,jine);
		}else {
			jines = jineMapper.findMoneyRecord1(paging,jine);
		}
		return jines;
	}

	@Override
	public Integer findMoneyRecordCounts(Jine jine) {
		int count = 0;
		if("2".equals(jine.getType())) {
			count = jineMapper.findMoneyRecordCounts2(jine);
		}else {
			count = jineMapper.findMoneyRecordCounts1(jine);
		}
		return count;
	}

	@Override
	public Integer findUserTikuanInfoCounts(Integer id) {
		return jineMapper.findUserTikuanInfoCounts(id);
	}

	@Override
	public Double findUserTikuanInfoSumMoney(Integer id) {
		return jineMapper.findUserTikuanInfoSumMoney(id);
	}


	@Transactional
	@Override
	public synchronized JsonResult quickRecharge(Jine jine, HttpSession session, String code) {
		if(null==jine.getFukuanje()||10.00>jine.getFukuanje()) {
			return new JsonResult("0","请填写正确的充值金额!");
		}
		User users = (User) session.getAttribute("user");
		SimpleDateFormat ss = new SimpleDateFormat("yyyyMMddHHmmss");
		User user = userMapper.getUserByid(users.getId());
		String orderNum = "CZ"+ss.format(new Date())+user.getId();
		if(user.getState() == 2) {
			return new JsonResult("0","试玩账号无法充值!");
		}
		List<Jine> jines = jineMapper.findByDateUserIdInfo(user.getId(),DateUtil.findFormatDate());
		if(jines.size()>2) {
			user.setStatu(1);
			userMapper.updateUserInfo(user); 
		}
		if(jines.size()>3) {
			if(code==null) {
				return new JsonResult("请输入验证码","请输入验证码!");
			}
			String icode = (String) session.getAttribute("code");
			if (!icode.toUpperCase().equals(code.toUpperCase())) {
				return new JsonResult("", "验证码输入不正确! ");
			} 
		}
		jine.setName(user.getName());
		jine.setOrdernum(orderNum);
		jine.setSqtime(DateUtil.getCurrTime());
		jine.setCltime(DateUtil.getCurrTime());
		jine.setType("人工加款");
		jine.setState("未处理");
		jine.setCaozuo("锁定");
		jine.setTikuanje(0.00);
		jine.setTikuansxf(0.00);
		jine.setUserid(user.getId());
		int b = jineMapper.addJilu(jine);
		int count = jineMapper.getCount();//websocket通知后台充值  请不要删除
		if(count > 0) {
			WebSocketJson w = new WebSocketJson(0,count);
			w.sendAllHt();
		}
		return new JsonResult("1", b);
	}

	@Override
	public JsonResult findUserCodeCount(User users, Double money) {
		User user = userMapper.getUserByid(users.getId());
		if (user.getState() == 2) {
			return new JsonResult("试玩账号不能提款", "试玩账号不能提款!");
		}
		int message = 1;
		Double stillNeedSth = 0.0;
		int count = jineMapper.findJineByStateSuccess(DateUtil.findFormatDate(), user.getId());//提款次数
		TodayRecord record = yunyingbbService.findOperateRecord("", "", user.getName(),2);
		double codeCount = record.getTouzhu();
		double drawingRatio = Double.parseDouble(WebsiteStateConfig.configs.get("drawingRatio"));
		double drawingMoney = Double.parseDouble(WebsiteStateConfig.configs.get("drawingMoney"));
		double dcountMoney = Double.parseDouble(WebsiteStateConfig.configs.get("dcountMoney"));
		int drawingFlag = Integer.parseInt(WebsiteStateConfig.configs.get("drawingFlag"));
		int meiritikuancount = Integer.parseInt(WebsiteStateConfig.configs.get("meiritikuancount"));
		double totalMoney = (record.getChongzhi()+record.getHuodong()) * drawingRatio;
		if (drawingFlag == 1) {
			if (codeCount < totalMoney) {
				message = 0;
				stillNeedSth = totalMoney - codeCount;
			}
		}
		String str = "";
		DecimalFormat dec = new DecimalFormat("#0.00");
		Double dm = drawingMoney * 100;
		if (count >= meiritikuancount) {
			Double cs = dcountMoney * 100;
			if (money == null) {
				str = "提款还需要打码" + dec.format(stillNeedSth) + "若要提款将收取" + dm + "%的手续费，并且你已超出每天提款次数，将收取你" + cs + "%"
						+ "的手续费,每天可免费提款" + meiritikuancount + "次";
			} else {
				str = "提款还需要打码" + dec.format(stillNeedSth) + "若要继续提款将收取" + dm + "%的手续费"
						+ drawingMoney * money + "元，并且你已超出每天提款次数，将收取你" + cs + "%" + "的手续费"
						+ dcountMoney * money + ",每天可免费提款" + meiritikuancount + "次";
			}
		} else {
			str = "提款还需要打码" + dec.format(stillNeedSth) + "若要提款将收取" + dm + "%的手续费";

		}
		return new JsonResult(message + "," + drawingMoney, str);
	}

	@Transactional
	@Override
	public synchronized JsonResult quickDrawing(Jine jine,User users, String zhifupass) {
		if(null==jine.getTikuanje()||100.00>jine.getTikuanje()) {
			return new JsonResult("0","请填写正确的提现金额!");
		}
		User user = userMapper.getUserByid(users.getId());
		if(user.getState() == 2) {
			return new JsonResult("0","试玩账号不能提款!");
		}
		double drawingRatio = Double.parseDouble(WebsiteStateConfig.configs.get("drawingRatio"));
		double drawingMoney = Double.parseDouble(WebsiteStateConfig.configs.get("drawingMoney"));
		double dcountMoney = Double.parseDouble(WebsiteStateConfig.configs.get("dcountMoney"));
		double maxMoney = Double.parseDouble(WebsiteStateConfig.configs.get("maxtikuanjine"));
		double minMoney = Double.parseDouble(WebsiteStateConfig.configs.get("mintikuanjine"));
		String stratchulitime = WebsiteStateConfig.configs.get("stratchulitime");
		String endchulitime = WebsiteStateConfig.configs.get("endchulitime");
		int drawingFlag = Integer.parseInt(WebsiteStateConfig.configs.get("drawingFlag"));
		int meiritikuancount = Integer.parseInt(WebsiteStateConfig.configs.get("meiritikuancount"));
		
		// 验证支付密码
		BankCard bank = bankMapper.checkPass(zhifupass, user.getId());
		// 充值总金额
		TodayRecord record = yunyingbbService.findOperateRecord("", "", user.getName(),2);
		// 是否有还在处理中的订单
		List<Jine> jines = jineMapper.findJineByState(user.getId());
		// 免费提款次数
		double damalCount = record.getTouzhu();
		int count = jineMapper.findJineByStateSuccess(DateUtil.findFormatDate(),user.getId());
		double totalMoney = (record.getChongzhi()+record.getHuodong()) * drawingRatio;
		double richang = jine.getTikuanje() * drawingMoney;//日常提款手续费
		double chaochu = jine.getTikuanje() * dcountMoney;//提款次数超出收续费
		// 支付密码
		if (bank == null) {
			return new JsonResult("0", "支付密码错误,发起提款失败!");
		}

		if (jine.getTikuanje() > maxMoney) {
			return new JsonResult("0", "金额超出最大提款金额,发起提款失败!");
		}
		if (jine.getTikuanje() < minMoney) {
			return new JsonResult("0", "金额小于最小提款金额,发起提款失败!");
		}
		//小时
		int currentHours = Integer.parseInt(DateUtil.findFormatDateHour().split("-")[0]);// 09:38:57  
		int startHours = Integer.parseInt(stratchulitime.substring(0, 2));
		int endHours = Integer.parseInt(endchulitime.substring(0, 2));
		//分钟
		int currentMinute = Integer.parseInt(DateUtil.findFormatDateHour().split("-")[1]);
		int endMinute = Integer.parseInt(endchulitime.substring(2, 4));
		if (endHours < startHours) {
			endHours += 24;
		}

		if(currentHours > endHours ) {
			return new JsonResult("0", "当前时间不在提款服务时间之内,请明日在进行提款!");
		}else {
			if(currentHours == startHours) {
				if(currentMinute < endMinute) {
					return new JsonResult("0", "当前时间不在提款服务时间之内,请明日在进行提款!");
				}
			}
			if(currentHours==Integer.parseInt(endchulitime.substring(0, 2))) {
				if(currentMinute > endMinute) {
					return new JsonResult("0", "当前时间不在提款服务时间之内,请明日在进行提款!");
				}
			}
		}
		if (jines.size()>0) {
			return new JsonResult("0", "已有正在处理中的提款订单,发起提款失败"); 
		}
		if (drawingFlag == 1) {
			if (damalCount >= totalMoney) {
				if (count >= meiritikuancount) {
					if (user.getBalance() < jine.getTikuanje() + chaochu) {
						return new JsonResult("0", "余额不足,发起提款失败!");
					} else {
						addTikuan(user, bank, jine, chaochu);
					}
				} else {
					if (user.getBalance() < jine.getTikuanje()) {
						return new JsonResult("0", "余额不足,发起提款失败!");
					} else {
						addTikuan(user, bank, jine, 0.00);
					}
				}
			} else {
				if (count >= meiritikuancount) {
					if (user.getBalance() < (jine.getTikuanje() + richang + chaochu)) {
						return new JsonResult("0", "余额不足,发起提款失败!");
					} else {
						addTikuan(user, bank, jine, richang + chaochu);
					}
				} else {
					if (user.getBalance() < jine.getTikuanje() + richang) {
						return new JsonResult("0", "余额不足,发起提款失败!");
					} else {
						addTikuan(user, bank, jine, richang);
					}
				}
			}
		} else {
			if (damalCount >= totalMoney) {
				if (count >= meiritikuancount) {
					if (user.getBalance() < jine.getTikuanje() + chaochu) {
						return new JsonResult("0", "余额不足,发起提款失败!");
					} else {
						addTikuan(user, bank, jine, chaochu);
					}
				} else {
					if (user.getBalance() < jine.getTikuanje()) {
						return new JsonResult("0", "余额不足,发起提款失败!");
					} else {
						addTikuan(user, bank, jine, 0.00);
					}
				}
			} else {
				return new JsonResult("0", "打码量不足,发起提款失败!");
			}
		}
		return new JsonResult("1", "发起提款成功,正在处理中!");
	}
	
/**
 *   方法名：addTikuan   
 *   描述：    添加提款信息                   TODO   
 *   参数：    @param user 用户信息
 *   参数：    @param bank 银行卡信息
 *   参数：    @param jine 充值金额信息
 *   参数：    @param amount 变动金额
 *   参数：    @return 
 * @return: int
 */
	public int addTikuan(User user, BankCard bank, Jine jine, double amount) {
		SimpleDateFormat ss = new SimpleDateFormat("yyyyMMddHHmmss");
		String orderNum = "TX" + ss.format(new Date()) + user.getId();
		AdminUser admin = new AdminUser();
		admin.setName("系统自动");
		jine.setName(user.getName());
		jine.setOrdernum(orderNum);
		jine.setSkname(bank.getXingming());
		jine.setZhifupt(bank.getKaihuhang());
		jine.setSkbankzh(bank.getBankNum());
		jine.setTikuansxf(amount);
		jine.setSqtime(DateUtil.getCurrTime());
		jine.setCltime(DateUtil.getCurrTime());
		jine.setType("在线提款");
		jine.setState("未处理");
		jine.setCaozuo("锁定");
		jine.setFukuanje(0.00);
		jine.setUserid(user.getId());
		jineMapper.addJilu(jine);
		liushuiService.drawingRecord(user, admin, orderNum, jine.getTikuanje(), null, "在线提款", 1);
		liushuiService.drawingRecord(user, admin, orderNum, amount, null, "提款手续费", 2);
		return 1;
	}

	@Transactional
	@Override
	public JsonResult rechargeAudit(AdminUser admin, Jine jine) {
		Jine jines = jineMapper.findByIdJineInfo(jine.getId());
		if ("充值成功".equals(jines.getState()) || "充值失败".equals(jines.getState())) {
			return new JsonResult("该订单已经处理过了,请勿重复处理!", "该订单已经处理过了,请勿重复处理!");
		}
		User user = userMapper.getUserByid(jine.getUserid());
		double amount = jine.getFukuanje();
		if (jine.getState().equals("充值成功")) {
			liushuiService.changeRecord(user, admin, jines.getOrdernum(), amount, null, "人工加款", 2);
			activityService.Recharge(user, jines.getOrdernum(), amount, "人工加款");
			new WebSocketJson(9,jine.getName(),"恭喜您充值成功到账"+jine.getFukuanje()+"元");
		} else {
			jine.setState("充值失败");
			new WebSocketJson(10,jine.getName(),"很遗憾你提交充值的"+jine.getFukuanje()+"元金额审核失败");
		}
		jine.setCzname(admin.getName());
		jine.setCltime(DateUtil.getCurrTime());
		return new JsonResult("success", jineMapper.upTikuanSh(jine));
	}

	@Transactional
	@Override
	public synchronized JsonResult drawingAudit(Jine jine, String states, AdminUser admin) {
		Jine data = jineMapper.findByIdJineInfo(jine.getId());
		if ("充值成功".equals(data.getState()) || "充值失败".equals(data.getState())) {
			return new JsonResult("该订单已经处理过了,请勿重复处理!", "该订单已经处理过了,请勿重复处理!");
		}
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		User user = userMapper.getUserByid(jine.getUserid());
		Jine jines = jineMapper.findByIdJineInfo(jine.getId());
		if (states.equals("信息有误")) {
			liushuiService.drawingRecord(user, admin, data.getOrdernum(), jine.getTikuanje(), null, "提款失败", 3);
			liushuiService.drawingRecord(user, admin, data.getOrdernum(), jines.getTikuansxf(), null, "手续费退还", 4);
			jine.setState("提款失败");
		}
		jine.setType("在线提款");
		jine.setCzname(admin.getName());
		jine.setCltime(sf.format(new Date()));
		jineMapper.upTikuanSh(jine);
		return new JsonResult("success", "提款成功,正在处理中!!");
	}

	@Override
	public synchronized JsonResult quickPayment(Jine jine, AdminUser admin) {
		SimpleDateFormat ss = new SimpleDateFormat("yyyMMddHHmmss");
		if (Integer.parseInt(WebsiteStateConfig.configs.get("kuaisucunkuanflag")) == 0)
			return new JsonResult("人工存款通道开关已关闭,请联系管理员开启!", null);
		int type = 0;
		String orderNum =  "";
		String key = jine.getType();
		double amount = jine.getFukuanje();
		User user = userMapper.getUserByid(jine.getUserid());
		// 内部账号
		if (user.getState() == 3) {
			if (key.equals("人工加款")) {
				orderNum =  "CZ"+ss.format(new Date())+jine.getUserid();
				type = 1;
				liushuiService.insideRecord(user, admin,orderNum,amount ,key,type);
			}else if("人工扣款".equals(key)){
				orderNum =  "TX"+ss.format(new Date())+jine.getUserid();
				type = 2;
				liushuiService.insideRecord(user, admin,orderNum,amount ,key,type);
			}
		} else {
			if (key.equals("人工加款")) {
				orderNum =  "CZ"+ss.format(new Date())+jine.getUserid();
				liushuiService.changeRecord(user, admin,orderNum, amount,jine, "人工加款", 2);
				activityService.Recharge(user, orderNum,amount, "人工加款");//充值活动赠送
			}else if("活动赠送".equals(key)){
				orderNum =  "CZ"+ss.format(new Date())+jine.getUserid();
				activityService.Recharge(user, orderNum,amount, "活动赠送");//充值活动赠送
			}else {
				orderNum =  "TX"+ss.format(new Date())+jine.getUserid();
				liushuiService.drawingRecord(user, admin,orderNum,amount,jine,"人工扣款", 5); //TODO:DD
			}
		}
		return new JsonResult("success", "操作成功!");
	}

	@Override
	public Integer getCount() {
		return jineMapper.getCount();
	}

	@Override
	public Integer getCountTk() {
		return jineMapper.getCountTk();
	}

	@Override
	public void timingTask(boolean takeInverse) {
		if(!JineServiceImpl.takeInverse){
			JineServiceImpl.takeInverse = takeInverse;
		}else{
			return;
		}
		while(JineServiceImpl.takeInverse){//循环请求查看用户是否充值成功
			List<PayMoney> pay1 = jineMapper.payMoney();//查询数据库里面还没有支付的订单
			List<PayMoney> pay = new ArrayList<PayMoney>();//数据库里面没超时的订单
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (PayMoney p : pay1) {//每查询一次数据  就要删除一次 超时的订单  是查询出来  集合里面的  不是数据库的
				Calendar cal = Calendar.getInstance();//获取时间对象
				try {
					cal.setTime(sdf.parse(p.getCreateTime()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				cal.add(Calendar.MINUTE, +10);
				if(cal.getTime().getTime() > new Date().getTime()){
					pay.add(p);//将没超时的订单放到新集合  请求查看是否已经付款
				}
			}
			for(PayMoney p : pay){
				if(p.getCreateTime() != null){
					Calendar cal = Calendar.getInstance();//获取时间对象
					try {
						cal.setTime(sdf.parse(p.getCreateTime()));
					} catch (ParseException e) {e.printStackTrace();}
					cal.add(Calendar.MINUTE, +10);
					JineServiceImpl.takeInverse = false;
					if(cal.getTime().getTime() > new Date().getTime()){
						findPaymentResult(p.getCardId());//查询订单是否已经支付
						JineServiceImpl.takeInverse = true;
					}
				}else{
					JineServiceImpl.takeInverse = false;//如果都是为null的话  结束循环
				}
			}
			try {
				Thread.sleep(30000);//30秒查询一次
			} catch (InterruptedException e) {e.printStackTrace();}
		}
	}


}